import React, { useState } from 'react'
import { Upload, message, Button } from 'antd'
import { UploadOutlined } from '@ant-design/icons'
import type { UploadProps, UploadFile as AntdUploadFile } from 'antd/es/upload/interface'

interface UploadFileProps extends Omit<UploadProps, 'onChange'> {
  value?: AntdUploadFile[]
  onChange?: (fileList: AntdUploadFile[]) => void
  maxSize?: number // MB
  accept?: string
}

const UploadFile: React.FC<UploadFileProps> = ({
  value,
  onChange,
  maxSize = 5,
  accept,
  ...props
}) => {
  const [fileList, setFileList] = useState<AntdUploadFile[]>(value || [])

  const handleChange: UploadProps['onChange'] = ({ fileList: newFileList }) => {
    setFileList(newFileList)
    onChange?.(newFileList)
  }

  const beforeUpload = (file: File) => {
    const isLtMaxSize = file.size / 1024 / 1024 < maxSize
    if (!isLtMaxSize) {
      message.error(`文件必须小于 ${maxSize}MB!`)
    }
    return isLtMaxSize
  }

  return (
    <Upload
      {...props}
      fileList={fileList}
      onChange={handleChange}
      beforeUpload={beforeUpload}
      accept={accept}
    >
      <Button icon={<UploadOutlined />}>点击上传</Button>
    </Upload>
  )
}

export default UploadFile 